import router from './router'
import store from './store'
// import axios from 'axios'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie

NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/login']// no redirect whitelist

router.beforeEach(async(to, from, next) => {
  var isNextDo = true
  NProgress.start() // start progress bar
  if (!isNextDo) return false
  // 是否是白名单免登陆
  if (whiteList.indexOf(to.path) !== -1) {
    next()
    NProgress.done()
    return true
  }
  // 判断未登录去登录
  if (!getToken()) {
    next({ name: 'Login', query: { redirectUrl: to.fullPath }})
    NProgress.done()
    return false
  }
  // //是否加载了用户数据
  if (store.state.user.userInfoStatus && store.state.user.userInfoStatus.loaded) {
    // 计算当前选中的resourceCode
    store.dispatch('auth/setActiveResourceCode', { $route: to })
    var { menuTree = [] } = store.state.auth
    var routeName = menuTree[0] && menuTree[0].children && menuTree[0].children[0] && menuTree[0].children[0].routeName ? menuTree[0].children[0].routeName : ''
    if (to.name === 'Dashboard' && routeName) {
      NProgress.done()
      return next({ name: routeName })
    }

    checkAuthIsPass(to, next)
    // NProgress.done()
  } else {
    // 权限相关
    return store.dispatch('user/getUserInfo').then(userInfo => {
      store.dispatch('auth/setMenuTree', userInfo).then(() => {
        // 计算当前选中的resourceCode
        store.dispatch('auth/setActiveResourceCode', { $route: to })
        var { menuTree = [] } = store.state.auth
        var routeName = menuTree[0] && menuTree[0].children && menuTree[0].children[0] && menuTree[0].children[0].routeName ? menuTree[0].children[0].routeName : ''

        if (to.name === 'Dashboard' && routeName) {
          NProgress.done()
          return next({ name: routeName })
        }
        checkAuthIsPass(to, next)
        // NProgress.done()
      }).catch(exp => {
        console.error(exp)
      })
    }).catch(msg => {
      Message({
        type: 'error',
        message: msg
      })
    })
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

function checkAuthIsPass($route, next) {
  store.dispatch('auth/checkAuthPathIsPass', { $route }).then(() => {
    next()
    NProgress.done()
  }).catch(msg => {
    next({ name: 'NoAccess' })
  })
}
